package com.haizhi.util;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.security.MessageDigest;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: youfeng
 * Date: 2018-06-22
 * Time: 12:10
 */

public class Md5Util {

    private static final Logger logger = LogManager.getLogger(Md5Util.class);

    private static MessageDigest md5 = null;

    static {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            logger.error("MD5实例初始化异常: ", e);
        }
    }

    /**
     * 用于获取一个String的md5值
     *
     * @param str 需要加密字符串
     * @return 返回加密后的字符串
     */
    public static String getMd5(String str) {
        byte[] bs = md5.digest(str.getBytes());
        StringBuilder sb = new StringBuilder(40);
        for (byte x : bs) {
            if ((x & 0xff) >> 4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString().toLowerCase();
    }

    public static void main(String[] args) {
        System.out.println(getMd5("hello world"));
    }
}